<template>
  <Dialog :title="dialogTitle" v-model="dialogVisible" align-center width="1200px">
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="7em"
      v-loading="formLoading"
    >
      <el-form-item label="放款金额" prop="loanAmount">
        <el-input-number
          v-model="formData.loanAmount"
          placeholder="请输入放款金额"
          :controls="false"
          :precision="2"
          align="left"
          :min="0"
          style="width: 100%;"
        >
          <template #suffix>元</template>
        </el-input-number>
      </el-form-item>
      <el-form-item label="佣金" prop="commission">
        <el-input-number
          v-model="formData.commission"
          placeholder="请输入佣金"
          :controls="false"
          :precision="2"
          align="left"
          :min="0"
          style="width: 100%;"
        >
          <template #suffix>元</template>
        </el-input-number>
      </el-form-item>
      <el-form-item label="点数" prop="points">
        <el-input-number
          v-model="formData.points"
          placeholder="请输入点数"
          :controls="false"
          align="left"
          :min="0"
          style="width: 100%;"
        >
          <template #suffix>元</template>
        </el-input-number>
      </el-form-item>
      <!-- <el-form-item label="押金" prop="deposit">
        <el-input v-model="formData.deposit" placeholder="请输入押金" />
      </el-form-item> -->
      <el-form-item label="放款银行" prop="bank">
        <el-select v-model="formData.bank" placeholder="请选择放款银行">
          <el-option
            v-for="dict in getIntDictOptions(DICT_TYPE.BANK)"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="放款时间" prop="loanTime">
        <el-date-picker
          style="width: 100%"
          v-model="formData.loanTime"
          type="datetime"
          value-format="x"
          format="YYYY-MM-DD HH:mm:ss"
          placeholder="选择放款时间"
        />
      </el-form-item>
      <!-- <el-form-item label="协助进件" prop="assist">
        <el-input v-model="formData.assist" placeholder="请输入协助进件" />
      </el-form-item> -->
      <el-form-item label="回款时间" prop="paymentCollectionTime">
        <el-date-picker
          style="width: 100%"
          v-model="formData.paymentCollectionTime"
          type="datetime"
          value-format="x"
          format="YYYY-MM-DD HH:mm:ss"
          placeholder="选择回款时间"
        />
      </el-form-item>
      <el-form-item label="签约合同" prop="signContract">
        <el-input v-model="formData.signContract" placeholder="请输入签约合同" />
      </el-form-item>
      <el-form-item label="签约时间" prop="signTime">
        <el-date-picker
          style="width: 100%"
          v-model="formData.signTime"
          type="datetime"
          value-format="x"
          format="YYYY-MM-DD HH:mm:ss"
          placeholder="选择签约时间"
        />
      </el-form-item>
      <el-form-item label="实际创收" prop="cost">
        <el-input v-model="formData.cost" placeholder="成本费" readonly />
      </el-form-item>
      <el-form-item label="" style="grid-column: 1 / -1; margin-top: -20px">
        <div style="color: #999; font-size: 12px">实际创收 = (放款金额 × 点数) ÷ 100 - 佣金</div>
      </el-form-item>
      <el-form-item label="是否转介绍" prop="referral">
        <el-radio-group v-model="formData.referral">
          <el-radio value="1">是</el-radio>
          <el-radio value="0">否</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="备注" prop="review" style="grid-column: 1 / -1">
        <el-input
          v-model="formData.review"
          placeholder="请输入备注"
          resize="none"
          :rows="4"
          type="textarea"
        />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="submitForm" type="primary" :disabled="formLoading">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>
</template>
<script setup lang="ts">
import { getIntDictOptions, DICT_TYPE } from '@/utils/dict'
import { loanApi, loan } from '@/api/system/loan'

/** 放款信息 表单 */
defineOptions({ name: 'LoanForm' })

const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗

const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formType = ref('') // 表单的类型：create - 新增；update - 修改
const formData = ref({
  id: undefined,
  customerId: undefined,
  followUserId: undefined,
  followUserName: undefined,
  loanAmount: 0,
  commission: 0,
  points: 0,
  bank: undefined,
  loanTime: undefined,
  paymentCollectionTime: undefined,
  signTime: undefined,
  signContract: undefined,
  deposit: undefined,
  cost: undefined,
  assist: undefined,
  referral: undefined,
  review: undefined
})
const formRules = reactive({
  customerId: [{ required: true, message: '新客户id不能为空', trigger: 'blur' }],
  followUserId: [{ required: true, message: '跟进用户id不能为空', trigger: 'blur' }],
  followUserName: [{ required: true, message: '跟进用户名称不能为空', trigger: 'blur' }],
  loanAmount: [
    { required: true, message: '放款金额不能为空', trigger: 'blur' },
    {
      validator(rule, value, callback) {
        return 0 < value ? callback() : callback(new Error('放款金额不能为0'));
      },
    },
  ],
  commission: [
    { required: true, message: '佣金不能为空', trigger: 'blur' },
    {
      validator(rule, value, callback) {
        return 0 < value ? callback() : callback(new Error('佣金不能为0'));
      },
    },
  ],
  points: [
    { required: true, message: '点数不能为空', trigger: 'blur' },
    {
      validator(rule, value, callback) {
        return 0 < value ? callback() : callback(new Error('点数不能为0'));
      },
    },
  ],
  bank: [{ required: true, message: '放款银行不能为空', trigger: 'change' }],
  loanTime: [{ required: true, message: '放款时间不能为空', trigger: 'blur' }],
  paymentCollectionTime: [{ required: true, message: '回款时间不能为空', trigger: 'blur' }]
})
const formRef = ref() // 表单 Ref

/** 打开弹窗 */
const open = async (type: string, id?: number, payload) => {
  dialogVisible.value = true
  dialogTitle.value = t('action.' + type)
  formType.value = type
  resetForm()
  formData.value.customerId = payload.customerId
  formData.value.customerName = payload.customerName;
  // 修改时，设置数据
  if (id) {
    formLoading.value = true
    try {
      formData.value = await loanApi.getloan(id)
    } finally {
      formLoading.value = false
    }
  }
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  // 校验表单
  await formRef.value.validate()
  // 提交请求
  formLoading.value = true
  try {
    const data = formData.value as unknown as loan
    if (formType.value === 'create') {
      await loanApi.createloan(data)
      message.success(t('common.createSuccess'))
    } else {
      await loanApi.updateloan(data)
      message.success(t('common.updateSuccess'))
    }
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success')
  } finally {
    formLoading.value = false
  }
}

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    id: undefined,
    customerId: undefined,
    followUserId: undefined,
    followUserName: undefined,
    loanAmount: 0,
    commission: 0,
    points: 0,
    bank: undefined,
    loanTime: undefined,
    paymentCollectionTime: undefined,
    signTime: undefined,
    signContract: undefined,
    deposit: undefined,
    cost: undefined,
    assist: undefined,
    referral: undefined,
    review: undefined
  }
  formRef.value?.resetFields()
}

// 计算 cost 值
const calculateCost = () => {
  const loanAmount = parseFloat(formData.value.loanAmount) || 0
  const points = parseFloat(formData.value.points) || 0
  const commission = parseFloat(formData.value.commission) || 0

  const cost = (loanAmount * points) / 100 - commission
  formData.value.cost = cost.toFixed(2)
}
// 监听相关字段的变化
watch(() => formData.value.loanAmount, calculateCost)
watch(() => formData.value.points, calculateCost)
watch(() => formData.value.commission, calculateCost)
</script>

<style scoped>
.el-form {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
}
</style>
